package liuds.music.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.RelativeLayout;


import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import liuds.music.App;
import liuds.music.model.RequestParams;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/5/23.
 */

public class Http {
    private final static int REQUEST_GET = 0;
    private final static int REQUEST_POST = 1;
    private static Handler mainHandle=new Handler(Looper.getMainLooper());

    public static final MediaType DEFAULT
            = MediaType.parse("application/x-www-form-urlencoded");
    public static final MediaType JSON
            = MediaType.parse("application/json");

    private static OkHttpClient client;

    public static OkHttpClient getOkHttpClient(){
        if(client == null){
            OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(20,TimeUnit.SECONDS);
            builder.writeTimeout(20,TimeUnit.SECONDS);

            builder.cookieJar(new CookieJar() {
                private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    cookieStore.put(url, cookies);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = cookieStore.get(url);
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            });

            client = builder.build();
        }
        return client;
    }

    private static void request(int Request_Method, String url, RequestParams params, final OnSuccessListener onSuccessListener
            , final OnErrorListener onErrorListener, final OnCompleteListener onCompleteListener, final boolean isOther){
        OkHttpClient client = getOkHttpClient();
        Request.Builder builder = new Request.Builder();

        if(isOther){

        }else{
            url = App.getUrl(url);
        }

        if(Request_Method == REQUEST_GET){
            builder.url(url).get();
        }else if(Request_Method == REQUEST_POST){
            RequestBody body = RequestBody.create(DEFAULT, params==null?"":params.toQueryParam());
            builder.url(url).post(body);
        }

        final Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mainHandle.post(new Runnable() {
                    @Override
                    public void run() {
                        String message = e.getMessage();
                        if(e instanceof SocketException || e instanceof UnknownHostException){
                            message = "网络连接超时";
                        }else{
                            if(onErrorListener!=null){
                                onErrorListener.onError(message);
                            }else{
                                Utils.toast(message);
                            }
                        }
                        if(onCompleteListener!=null){
                            onCompleteListener.onComplete();
                        }
                    }
                });

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                mainHandle.post(new Runnable() {
                    @Override
                    public void run() {
                        App.log("Http : "+result);
                        if(isOther){
                            if(onSuccessListener!=null){
                                onSuccessListener.onSuccess(result);
                            }
                            if(onCompleteListener!=null){
                                onCompleteListener.onComplete();
                            }
                        }else{
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                int code = jsonObject.optInt("code");
                                if(code == 0){
                                    if(onSuccessListener!=null){
                                        onSuccessListener.onSuccess(jsonObject.opt("data"));
                                    }
                                }else{
                                    if(onErrorListener!=null){
                                        onErrorListener.onError(jsonObject);
                                    }else{
                                        Utils.toast(jsonObject.optString("message"));
                                    }
                                }
                                if(onCompleteListener!=null){
                                    onCompleteListener.onComplete();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                if(onCompleteListener!=null){
                                    onCompleteListener.onComplete();
                                }
                                Utils.toast(e.getMessage());
                            }
                        }
                    }
                });
            }
        });
    }

    public static void getOther(String url,OnSuccessListener onSuccessListener,OnErrorListener onErrorListener,OnCompleteListener onCompleteListener){
        request(REQUEST_GET,url,null,onSuccessListener,onErrorListener,onCompleteListener,true);
    }

    public static void postOther(String url,RequestParams params,OnSuccessListener onSuccessListener,OnErrorListener onErrorListener,OnCompleteListener onCompleteListener){
        request(REQUEST_POST,url,params,onSuccessListener,onErrorListener,onCompleteListener,true);
    }

    public static void get(String url,OnSuccessListener onSuccessListener,OnErrorListener onErrorListener,OnCompleteListener onCompleteListener){
        request(REQUEST_GET,url,null,onSuccessListener,onErrorListener,onCompleteListener,false);
    }

    public static void post(String url,RequestParams params,OnSuccessListener onSuccessListener,OnErrorListener onErrorListener,OnCompleteListener onCompleteListener){
        request(REQUEST_POST,url, params,onSuccessListener,onErrorListener,onCompleteListener,false);
    }

    public interface OnSuccessListener{
        void onSuccess(Object result);
    }

    public interface OnErrorListener{
        void onError(Object message);
    }

    public interface OnCompleteListener{
        void onComplete();
    }
}
